package com.szh.gulimall.product.exception;

import com.szh.common.constant.GulimallCodeEnum;
import com.szh.common.utils.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: SongZiHao
 * @date: 2022/11/5
 */
@RestControllerAdvice(basePackages = "com.szh.gulimall.product.controller")
public class GulimallExceptionControllerAdvice {

    private static final Logger LOGGER = LoggerFactory.getLogger(GulimallExceptionControllerAdvice.class);

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException ex) {
        LOGGER.error("数据校验出现问题：{}，异常类型：{}", ex.getMessage(), ex.getClass());
        BindingResult bindingResult = ex.getBindingResult();
        Map<String, String> errorMap = new HashMap<>();
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        for (FieldError fieldError : fieldErrors) {
            errorMap.put(fieldError.getField(), fieldError.getDefaultMessage());
        }
        return R.error(GulimallCodeEnum.VALID_EXCEPTION.getCode(), GulimallCodeEnum.VALID_EXCEPTION.getMsg())
                .put("data", errorMap);
    }

    @ExceptionHandler(value = Exception.class)
    public R handleException(Exception ex) {
        LOGGER.error("全局异常：{}，异常类型：{}", ex.getMessage(), ex.getClass());
        Map<String, String> errorMap = new HashMap<>();
        errorMap.put("error", ex.getMessage());
        return R.error(GulimallCodeEnum.UNKNOWN_EXCEPTION.getCode(), GulimallCodeEnum.UNKNOWN_EXCEPTION.getMsg())
                .put("data", errorMap);
    }
}
